﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Tools.Helper
{
    public delegate void InvokeScriptCompletedEventHandler(InvokeScriptCompletedEventArgs e);
    public class InvokeScriptCompletedEventArgs : EventArgs
    {
        object _result;
        public InvokeScriptCompletedEventArgs(object obj)
        {
            _result = obj;
        }
        public object Result
        {
            get
            {
                return _result;
            }
        }
    }
    public class JavascriptHelper
    {
        public event InvokeScriptCompletedEventHandler InvokeScriptCompleted;

        WebBrowser webBrowser;
        string scriptName;
        object[] args;

        public JavascriptHelper()
        {
            webBrowser = new WebBrowser();
            webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser_DocumentCompleted);
        }

        void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            object retuanVal = webBrowser.Document.Window.Document.InvokeScript(scriptName, args);
            if (this.InvokeScriptCompleted != null)
            {
                InvokeScriptCompleted(new InvokeScriptCompletedEventArgs(retuanVal));
            }
        }

        string InitHtml(StringBuilder scriptBuilder)
        {
            string html = @"
<!doctype html>
<html>
<head>
    {0}
</head>
<body>
</body>
</html>
    ";
            return string.Format(html, scriptBuilder.ToString());
        }

        public void AddScriptSrc(StringBuilder scriptBuilder, string scriptPath)
        {
            scriptBuilder.AppendLine(string.Format("<script src='{0}'></script>", scriptPath));
        }

        public void AddScriptBlock(StringBuilder scriptBuilder, string scriptBlock)
        {
            scriptBuilder.AppendLine(string.Format("<script type='text/javascript'>{0}</script>", scriptBlock));
        }

        public void InvokeScriptAsync(StringBuilder scriptBuilder, string scriptName, object[] args)
        {
            string html = InitHtml(scriptBuilder);
            webBrowser.Navigate("about:blank");
            webBrowser.DocumentText = html;
            webBrowser.Document.Write(html);

            this.scriptName = scriptName;
            this.args = args;
        }
    }
}
